package com.xiaozhichao.hadoop.zk;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.GetDataBuilder;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

public class CuratorDemo {

    public static CuratorFramework connect(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client =
                CuratorFrameworkFactory.builder()
                        .connectString("127.0.0.1:2181")
                        .sessionTimeoutMs(5000)
                        .connectionTimeoutMs(5000)
                        .retryPolicy(retryPolicy)
                        .build();
        client.start();
        return client;
    }

    public static void create(CuratorFramework client, String key, String value, CreateMode type){
        try {
            client.create().withMode(type).forPath(key,value.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] search(CuratorFramework client, String key){
        GetDataBuilder data = client.getData();
        byte[] dubboPath = null;
        try {
            dubboPath = data.forPath(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dubboPath;
    }

    public static void addListener(CuratorFramework client){
        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if(newState == ConnectionState.CONNECTED){
                    System.out.println("Listener CONNECTED ...");
                }else if(newState == ConnectionState.LOST){
                    System.out.println("Listener LOST ...");
                }else if(newState == ConnectionState.RECONNECTED){
                    System.out.println("Listener RECONNECTED ...");
                }
            }
        });
    }


    public static void main(String[] args) {
        CuratorFramework client = CuratorDemo.connect();
        CuratorDemo.addListener(client);
        CuratorDemo.create(client,"/demo","http://demo:port/",CreateMode.EPHEMERAL);
        System.out.println(new String(CuratorDemo.search(client,"/demo")));

    }
}
